<?php
// get name of request
if(!$_GET['show'] == "") {
  $req = $_GET['show'];
}
if(!$_GET['edit'] == "") {
  $req = $_GET['edit'];
}
// normalize the title for later use (caps, etc)
$title = sqlite_fetch_single(sqlite_query($db,"SELECT title FROM pages WHERE title LIKE '$req'"));
if(!$title) {
  $title = $req;
}
// flow (needs getPage() function!)
if(!$_GET['show'] == "") {
  if($_GET['show'] == "_index") {
    // list all pages
    $doctitle = "/pages";
    $header = $doctitle;
    $content = "listpages.php";
    $pages = sqlite_fetch_all(sqlite_query($db,"SELECT * FROM pages"));
  } else if($_GET['show'] == '_revisions') {
    // list recent revisions
    $doctitle = "/revisions";
    $header = $doctitle;
    $content = "listrevisions.php";
  } else {
    // show page
    $page = sqlite_fetch_array(sqlite_query($db,"SELECT * FROM pages WHERE title LIKE '$title'"));
	$doctitle = "/pages/$title";
	$header = "/<a href='?show=_index'>pages</a>/$title";
    if($page) {
      $revisions = sqlite_fetch_all(sqlite_query($db,"SELECT * FROM revisions WHERE pageid=".$page['id']." ORDER BY time"));
      if($_GET['revision'] == "") {
        // latest
        $currentrevision = count($revisions);
      } else {
        // certain revision
        $doctitle .= "/".$_GET['revision'];
        $header = "/<a href='?show=_index'>pages</a>/<a href='?show=$title'>$title</a>/".$_GET['revision'];
        $currentrevision = $_GET['revision'];
      }
      $content = "show.php";
    } else {
      $content = "notfound.php";
    }
  }
} else if(!$_GET['edit'] == "") {
  // edit page
  $doctitle = "/pages/$title/edit";
  $header = "/<a href='?show=_index'>pages</a>/<a href='?show=$title'>$title</a>/edit";
  $content = "edit.php";
  $page = sqlite_fetch_array(sqlite_query($db,"SELECT * FROM pages WHERE title LIKE '$title'"));
  $revision = sqlite_fetch_array(sqlite_query($db,"SELECT * FROM revisions WHERE pageid=".$page['id']." ORDER BY time DESC"));
} else if(!$_GET['tag'] == "") {
  $tag = $_GET['tag'];
  if($tag == "_index") {
    // list tags
    $doctitle = "/tags";
    $header = $doctitle;
    $content = "listtags.php";
  } else {
    // list pages tagged something
    $doctitle = "/tags/$tag";
    $header = "/<a href='?tag=_index'>tags</a>/$tag";
    $content = "listpages.php";
    $pages = sqlite_fetch_all(sqlite_query($db,"SELECT * FROM pages WHERE tags LIKE '%$tag%'"));
  }
} else {
  // main page
  header("location: index.php?show=main");
}
?>